package com.tao.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ALiOSSUtil {
    private String endPoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    public String upload(MultipartFile file) throws Exception{
        log.info("\nendPoint:{}\naccessKeyId:{}\nacessKeySecret:{}\nbucketName:{}",endPoint,accessKeyId,accessKeySecret,bucketName);
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId,accessKeySecret);
        InputStream is = file.getInputStream();
        String fileName = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        ossClient.putObject(bucketName,fileName,is);
        log.info("成功进行云存储");
        String url = "https://" + bucketName + '.' + endPoint.split("//")[1] +"/" + fileName;
        log.info("文件URL:{}",url);
        return url;
    }
}
